<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-16
 * Time: 16:01
 * 创建余额订单类
 */

namespace app\api\service\money;


use app\api\model\Cost;
use app\api\model\MoneyOrder;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class MoneyOrderSer extends Token
{
    // 充值金额ID
    private $costId;

    // 充值金额
    private $money;

    // 充值金额信息
    private $costInfo;

    // 用户ID
    private $uid;

    function __construct($costId,$money)
    {
        $this->costId = $costId;
        $this->money = $money;
    }

    // 创建会员支付订单入口
    public function place()
    {
        $this->getInfo();
        $this->getUserInfo();
        return $this->createOrder();
    }

    // 获取会员费详情
    private function getInfo()
    {
        $this->costInfo = Cost::get($this->costId);
        if(!$this->costInfo) {
            $this->costId = 0;
            if($this->money <= 0) {
                throw new ParameterException([
                    'msg' => [
                        'money' => '请重新选择支付信息'
                    ]
                ]);
            }
        }
    }

    // 获取用户信息
    private function getUserInfo()
    {
        $this->uid = self::getCurrentUid();
    }

    // 创建订单
    private function createOrder()
    {
        MoneyOrder::destroy([ 'user_id' => $this->uid, 'status'=>1 ]);
        if($this->costInfo) {
//            $price = round($this->costInfo['price']*($this->costInfo['discount']/10),2);
//            $money = round($this->costInfo['price'] - $price,2);
//            if($money < 0) {
//                throw new ParameterException([
//                    'msg' => [
//                        'money' => '折扣信息错误'
//                    ]
//                ]);
//            }
            $price = $this->costInfo['price'];
            $money = 0;
        } else {
            $price = $this->money;
            $money = 0;
        }
        // 创建订单
        Db::startTrans();
        try{
            $mode = MoneyOrder::create([
                'user_id' => $this->uid,
                'cost_id' => $this->costId,
                'price' => $price,
                'money' => $money,
                'order_no' => self::makeOrderNo()
            ]);
            $out_trade_no = '1zheng2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}